<?php

namespace app\common\lib\mini\alipay;

/**
 *$rsa2 = new Rsa2();
 *$data = 'mydata'; //待签名字符串
 *$strSign = $rsa2->createSign($data);      //生成签名
 *$is_ok = $rsa2->verifySign($data, $strSign); //验证签名
 */
class RsaHelper
{

    private static $PRIVATE_KEY;
    private static $PUBLIC_KEY;


    public function __construct($config = null)
    {
        if ($config)
        {
            self::$PRIVATE_KEY = $config['private_key'];
            self::$PUBLIC_KEY = $config['publick_key'];
        } else
        {
            self::$PRIVATE_KEY = config('mini')['ALIPAY']['private_key'];
            self::$PUBLIC_KEY = config('mini')['ALIPAY']['publick_key'];
        }
    }

    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        $privKey = '-----BEGIN RSA PRIVATE KEY-----' . PHP_EOL . wordwrap($privKey, 64, PHP_EOL, true) . PHP_EOL . '-----END RSA PRIVATE KEY-----';
        ($privKey) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        error_log('private_key is ===========>: ' . $privKey);
        return openssl_pkey_get_private($privKey);
    }

    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {
        $publicKey = self::$PUBLIC_KEY;
        $publicKey = '-----BEGIN RSA PRIVATE KEY-----' . PHP_EOL . wordwrap($publicKey, 64, PHP_EOL, true) . PHP_EOL . '-----END RSA PRIVATE KEY-----';
        error_log('public key is : ===========>' . $publicKey);
        return openssl_pkey_get_public($publicKey);
    }

    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = '')
    {
        //  var_dump(self::getPrivateKey());die;
        if (!is_string($data))
        {
            return null;
        }
        return openssl_sign($data, $sign, self::getPrivateKey(), OPENSSL_ALGO_SHA256) ? base64_encode($sign) : null;
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign))
        {
            return false;
        }
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA256
        );
    }
}
